﻿#include "mainwindow.h"

#include <QApplication>
#include <QMutex>
#include <QDateTime>
#include <QFile>
#include <QFileInfo>
#include <QTextStream>
#include <QProcessEnvironment>

#define LOG_FILE_NAME "log.txt"
#define MAX_LOG_SIZE 10 * 1024 * 1024

void outputLogMessage(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    static QMutex mutex;

    bool ok;
    int logLevel = QProcessEnvironment::systemEnvironment().value("UT_LOG_LEVEL").toInt(&ok, 10);
    if (!ok)
        logLevel = 2;

    if ((int)type < logLevel)
        return;

    QString text;

    switch (type)
    {
    case QtDebugMsg:
        text = QString("[Debug]");
        break;

    case QtInfoMsg:
        text = QString("[Info]");
        break;

    case QtWarningMsg:
        text = QString("[Warning]");
        break;

    case QtCriticalMsg:
        text = QString("[Critical]");
        break;

    case QtFatalMsg:
        text = QString("[Fatal]");
    }

    text.append(QString(" [%1] ").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss zzz")));
    text.append(QString(" [%1: Line: %2] ").arg(context.file).arg(context.line));
    text.append(QString(" [Function: %1] ").arg(context.function));

    mutex.lock();

    QString logFileName = QString("%1/%2").arg(qApp->applicationDirPath()).arg(LOG_FILE_NAME);
    if (QFileInfo::exists(logFileName)) {
        QFileInfo fileInfo(logFileName);
        if (fileInfo.size() > MAX_LOG_SIZE) {
            QString logBakFileName = logFileName.append(".bak");
            QFile::remove(logBakFileName);
            QFile::rename(logFileName, logBakFileName);
        }
    }

    QFile file(logFileName);
    file.open(QIODevice::WriteOnly | QIODevice::Append);
    QTextStream textStream(&file);
    textStream << text << endl << QString("Message: %1").arg(msg) << endl;
    file.close();

    mutex.unlock();
}

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    qInstallMessageHandler(outputLogMessage);
    MainWindow w;
    w.show();
    return a.exec();
}
